package com.qf.web;

import com.alibaba.fastjson.JSON;
import com.qf.model.Card;
import com.qf.model.Massage;
import com.qf.model.User;
import com.qf.service.AccountService;
import com.qf.service.CardService;
import com.qf.service.UserService;
import com.qf.service.impl.AccountServiceImpl;
import com.qf.service.impl.CardServiceImpl;
import com.qf.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.Callable;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;
@WebServlet("/cardServlet")
public class CardServlet extends BascServlet{
    CardService cardService = new CardServiceImpl();
    AccountService accountService = new AccountServiceImpl();
    UserService userService = new UserServiceImpl();
    //添加申请的信用卡信息 非事务
    protected void applyCreditCard(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取开户行
        int c_account = Integer.parseInt(req.getParameter("c_account"));//-1:未选择开户行 1:中国银行 2:中国邮政 3:中国农业银行
        //获取手机号
        String c_phone = req.getParameter("u_phone");
        //获取验证码
        String code = req.getParameter("code");
        //获取用户id
        int u_id = Integer.parseInt(req.getParameter("u_id"));
        //判断验证码,从session域中取到验证码
        String attribute = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);

        Massage m = null;
        /*if(!attribute.equals(code)){
            //添加申请信息
            m = new Massage<>(-1,"验证码错误");
        }else if(c_account == -1){
            m = new Massage<>(-2,"未选择开户行");
        }else {
            //调用方法
            String account="";
            if(c_account == 1){
                account="中国银行";
            }else if(c_account == 2){
                account="中国邮政";
            }else {
                account="中国农业银行";
            }
            int update = cardService.addCreditCard(u_id,account,c_phone);
            if(update == 1){
                m = new Massage(1,"信用卡申请成功,审核时间为两个工作日以内，请您耐心等待");
            }else {
                m = new Massage(-3,"信用卡申请失败！");
            }
        }
        String s = JSON.toJSONString(m);
        resp.getWriter().write(s);*/

        //改进
        if(!attribute.equals(code)){
            //添加申请信息
            m = new Massage<>(-1,"验证码错误");
        }else if(c_account == -1){
            m = new Massage<>(-2,"未选择开户行");
        }else {
            String account="";
            if(c_account == 1){
                account="中国银行";
            }else if(c_account == 2){
                account="中国邮政";
            }else {
                account="中国农业银行";
            }
            //调用查询所有的
            List<Card> list = cardService.findCreditCardAll(u_id);
            int flag = 0;
            for (int i = 0;i < list.size();i++){
                if(list.get(i).getC_account().equals(account)){
                    flag = 1;
                }
            }
            if(flag == 0){
                //可以申请
                int update = cardService.addCreditCard(u_id,account,c_phone);
                if(update == 1){
                    m = new Massage(1,"信用卡申请成功,审核时间为两个工作日以内，请您耐心等待");
                }else {
                    m = new Massage(-3,"信用卡申请失败！");
                }
            }else {
                m = new Massage(-2,"已申请过该银行的信用卡");
            }
        }
        String s = JSON.toJSONString(m);
        resp.getWriter().write(s);
    }

    //根据用户id查询用户是否具有可使用的储蓄卡
    protected void findDepositCard(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //获取用户id
        int u_id = Integer.parseInt(req.getParameter("userid"));
        //调用查询方法
        List<Card> list = cardService.findDepositCardByU_id(u_id);
        Massage<List<Card>> m = null;

        if(list == null || list.size() == 0){
            m = new Massage<>(-1,"该用户没有储蓄卡");
        }else {
            m = new Massage<>(1,"查询成功",list);
        }
        String s = JSON.toJSONString(m);
        resp.getWriter().write(s);
    }

    //信用卡还款 事务
    protected void creditCardRepayment(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //获取支付密码
        String pwd = req.getParameter("pwd");
        //获取用户id
        int u_id = Integer.parseInt(req.getParameter("userid"));
        //获取还款金额
        double amount = Double.parseDouble(req.getParameter("amount"));
        //获取待还款的信用卡卡号
        String rep_creditCard = req.getParameter("rep_creditCard");
        //获取转出账户
        String out_card = req.getParameter("out_card");

        //根据用户id查询用户信息
        User user = userService.findByUid(u_id);
        //查找待还款的信用卡
        Card rep_card = cardService.findCreditCardByC_id(rep_creditCard);
        //查询用于还款的储蓄卡
        Card sav_card = accountService.findCardByCid(out_card);

        Massage m = null;
        if(out_card.equals("-1")){
            m = new Massage(-1,"未选择还款方式");
        }else if(out_card.equals("1")){
            //app支付密码的判断
            if(!pwd.equals(user.getU_cpwd())){
                m = new Massage(-1,"app支付密码错误,请重新输入");
            }
            //app余额支付
            //根据用户id查询用户信息
            //验证余额是否充足
            else if(user.getU_balance() > amount){
                //余额充足，可以还款
                //1.app还款
                //2.添加还款记录

                //user ：用户对象
                //card ：银行卡对象 （使用用户app余额付款时可以为空）
                //amount：需要还款金额
                //p：   1：app扣款  2：表示：银行卡扣款
                //double amount, int p, User user, Card card
                int i= cardService.creditCardRepayment(amount,1,user,rep_card,sav_card);
                if(i==1){
                    m=new Massage(1,"还款成功");
                }else {
                    m=new Massage(-1,"还款失败，请重新尝试");
                }

            }else {
                //余额不足，返回信息
                m=new Massage(-1,"app余额不足，请更换支付方式");
            }
        }else {
            if(!pwd.equals(sav_card.getC_pwd())){
                m = new Massage(-1,"储蓄卡支付密码错误，请重新输入");
            }
            //使用银行卡号付款
            //验证银行卡余额是否充足
            else if(sav_card.getC_balance() > amount){
                //余额充足，可以还款
                //1.银行卡扣款
                //2.添加还款记录
                //user ：用户对象
                //money：需要还款金额
                //p：   1：app扣款  2：表示：银行卡扣款
                //double amount, int p, User user, Card card
                int i= cardService.creditCardRepayment(amount,2,user,rep_card,sav_card);
                if(i==1){
                    m=new Massage(1,"还款成功");
                }else {
                    m=new Massage(-1,"还款失败");
                }
            }else {
                //余额不足，返回信息
                m=new Massage(-1,"银行卡余额不足，请更换还款方式");
            }
        }
        String s = JSON.toJSONString(m);
        resp.getWriter().write(s);
    }

    //根据信用卡号，查询信用卡信息
    protected void findCreditCard(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //获取信用卡号
        String c_id = req.getParameter("c_id");
        //调用查询方法
        Card card = cardService.findCreditCardByC_id(c_id);
        Massage<Card> m = null;
        if(c_id.equals("-1")){
            m = new Massage<>(-1,"未选择信用卡!");
        }
        if(card != null){
            m = new Massage<>(1,"查询成功",card);
        }else {
            m = new Massage<>(-1, "查询失败");
        }
        String s = JSON.toJSONString(m);
        resp.getWriter().write(s);
    }

    //审核或者拒绝未审核的银行卡
    public  void updateCard(HttpServletRequest req, HttpServletResponse resp)throws  Exception{
        int id =Integer.parseInt(req.getParameter("id")) ;  //银行卡信息编号
        int type=Integer.parseInt(req.getParameter("type"));//1：审核通过，2：拒绝开户

        int i=cardService.updateCard(id,type);
        Massage m=null;
        if(i==1){
            m=new Massage(1,"操作成功");
        }else {
            m=new Massage(-1,"审核失败");

        }
        String s = JSON.toJSONString(m);
        resp.getWriter().write(s);
    }


    //进度查询
    protected void findSchedule(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        int u_id = Integer.parseInt(req.getParameter("u_id"));
        //调用查询所有的信用卡的方法
        List<Card> list1 = cardService.findCreditCardAll(u_id);
        //调用查询审批未通过的信用卡
        List<Card> list2 = cardService.findCreditCardUnusable(u_id);
        Massage m = null;
        if(list1.size() == 0){
            //没有申请过信用卡
            m = new Massage(-1,"您还没有申过信用卡!");
        }else if(list2.size()>0){
            int j =0;//没有待审核   0:待审核的  >0：已经被拒绝
            for(int i=0;i<list1.size();i++){
                if(list1.get(i).getC_check()==0){
                    j+=1;
                }
            }
            if(j>0){
                //存在未审核通过的信用卡
                m = new Massage(2,"正在审核中,审核结果将在两个工作日内返回,请您耐心等待！");
            }else {
                //存在未审核通过的信用卡
                m = new Massage(2,"申请已经被拒绝，请隔一段时候后重新申请");
            }
        }else if(list2.size() == 0){
            m = new Massage(1,"审核通过!");
        }
        String s = JSON.toJSONString(m);
        resp.getWriter().write(s);
    }

    //取款,根据用户id查询用户是否有主卡
    protected void findHostCard(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        int u_id = Integer.parseInt(req.getParameter("userid"));
        //查询用户是否有主卡
        List<Card> list = cardService.findHostCard(u_id);
        Massage<List<Card>> m = null;
        if(list.size() > 0){
            m = new Massage<>(1,"存在主卡",list);
        }else {
            m = new Massage<>(-1,"不存在主卡");
        }
        String s = JSON.toJSONString(m);
        resp.getWriter().write(s);
    }

    //信用卡转出 事务
    protected void creditCardOut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //获取用户输入的密码
        String c_pwd = req.getParameter("pwd");
        //获取用户id
        int u_id = Integer.parseInt(req.getParameter("u_id"));
        //获取转出账户
        String out_card = req.getParameter("out_card");
        //获取转入账户
        String in_card = req.getParameter("in_card");
        //获取转出金额
        Double money = Double.parseDouble(req.getParameter("money"));
        //获取总手续费
        Double serviceCharge = Double.parseDouble(req.getParameter("serviceCharge"));
        //成功转入账户的最终金额
        Double amount = money - serviceCharge;
        //根据用户id查询用户信息
        User user = userService.findByUid(u_id);
        //查找待转出的信用卡
        Card creditCard = cardService.findCard(out_card);
        //查找接收转出金额的主卡
        Card masterCard = cardService.findCard(in_card);
        Massage m = null;
        if(!c_pwd.equals(creditCard.getC_pwd())){
            m = new Massage(-1,"支付密码错误，请重新尝试!");
        }else if(out_card.equals("-1") || in_card.equals("-1")){
            m = new Massage(-1,"未选择转出信用卡或转入账户!");
        }else {
            if(creditCard.getC_balance() >= money){
                if(in_card.equals("1")){
                    //用户app余额接收转出
                    //String in_card,String out_card,User user,Double amount,int p
                    int update = cardService.creditCardOut(null,creditCard,user,amount,1,money);
                    if(update > 0){
                        m = new Massage(1,"信用卡转出到账户余额成功!");
                    }else {
                        m = new Massage(-1,"信用卡转出到账户余额失败!");
                    }
                }else {
                    //用户主卡接收转出金额
                    int update = cardService.creditCardOut(masterCard,creditCard,user,amount,2,money);
                    if(update > 0){
                        m = new Massage(1,"信用卡转出到主卡成功!");
                    }else {
                        m = new Massage(-1,"信用卡转出到主卡失败!");
                    }
                }
            }else {
                m = new Massage(-1,"信用卡额度不足!");
            }
        }
        String s = JSON.toJSONString(m);
        resp.getWriter().write(s);



    }

}
